const { secret } = require('../../config/global');
const md5 = require('md5');
// 导入jwt
const jwt = require('jsonwebtoken');
// 导入数据库查询方法
const { getOne, query } = require('../../utils/dbTools');
const { arrToTree, createLog } = require('../../utils/util');

// 数据表名称
const tableName = 'admin';
const roleTableName = 'role';
const menuTableName = 'menu';


// 登录处理函数
const login = async (req, res) => {
    const output = {
        code: 200,
        msg: '登录成功'
    }
    // 获取请求参数
    let { username, password } = req.body;
    if (!username || !password) {
        output.code = 500;
        output.msg = '参数错误, 未提交账号或密码';
        return res.send(output);
    }
    // 对密码进行MD5加密
    password = md5(password.toString());
    const result = await getOne(tableName, { username, password });
    if (!result) {
        output.code = 500;
        output.msg = '账号或密码错误';
        return res.send(output);
    }
    if (result.status === 2) {
        output.code = 500;
        output.msg = '账号被禁用';
        return res.send(output);
    }
    const { rid } = result
    // 生成登录凭证token
    const token = jwt.sign({ id: result.id, rid, username }, secret, { expiresIn: 60 });
    // 生成refresh_token
    const refresh_token = jwt.sign({ id: result.id, rid, username }, secret, { expiresIn: '2h' });
    output.data = {
        ...result,
        token,
        refresh_token
    }
    // 删除密码
    delete output.data.password;
    // 记录登录日志
    createLog(req, { accountid: result.id, type: 1, remark: "登录系统" })
    // 查询账号全选数据
    const permission = await getPermission(result.rid);
    output.data.permission = permission;
    res.send(output);
}

// token续费
const refreshToken = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功',
    }
    // 获取refresh_token
    const refresh_token = req.body.refresh_token;
    try {
        // 解析refresh_token
        var decoded = jwt.verify(refresh_token, secret);
        if (!decoded) {
            output.code = 405;
            output.msg = 'refresh_token不合法或已过期';
            return res.send(output);
        }
        const { exp } = decoded;
        // token过期
        if (exp * 1000 < Date.now()) {
            output.code = 405;
            output.msg = "refresh_token已过期";
            return output;
        }
        // refresh_token中保存的数据{id,role_id,phone}
        const { id, rid, username } = decoded
        // 重新生成token
        const newToken = jwt.sign({ id, rid, username }, secret, { expiresIn: '1h' });
        // 重新生成refresh_token
        const newRefreshToken = jwt.sign({ id, rid, username }, secret, { expiresIn: '2h' });
        output.data = {
            token: newToken, refresh_token: newRefreshToken
        }
        return res.send(output)
    } catch (err) {
        // err
        if (!decoded) {
            output.code = 405;
            output.msg = 'refresh_token不合法或已过期';
            return res.send(output);
        }
    }
    res.send(output)
}



// 检查token是否过期
const checkToken = async (req, res) => {
    const { authorization } = req.headers;
    // 验证token是否合法
    const output = verifyToken(authorization)
    res.send(output);
}

// 查询账号权限
// rid: 角色id

const getPermission = async (rid) => {
    const result = await getOne(roleTableName, { id: rid });
    if (result) {
        let sql = `select * from ${menuTableName} where id in (${result.permission})`;
        const ret = await query(sql);
        if (ret) {
            // 将普通数组转为树形数组
            return arrToTree(ret)
        }
        return [];
    }
}

module.exports = { login, refreshToken,checkToken };


